﻿using System;
using System.Data.Linq;

namespace OneSystems.Data
{
    /// <summary>
    /// Creates a defined scope of operation for DataContext
    /// </summary>
    /// <remarks>
    /// The scope of the DataContext affects TransactionScope
    /// as well as the use of DataLoadOptions. DataContextScope
    /// was created in order to explicitly control these 
    /// objects and their settings
    /// </remarks>
    public class DataContextScope : IDisposable
    {
        private String m_ContextKey = String.Empty;
        private DataLoadOptions m_Options;
        private static Random m_Random = new Random();

        /// <summary>
        /// optional ctor
        /// </summary>
        /// <param name="options">Defined DataLoadOptions for the current scope.</param>
        /// <remarks>DataLoadOptions must be defined before DataContext is
        /// created, so they must be fully defined before passing them to
        /// this ctor.</remarks>
        public DataContextScope(DataLoadOptions options)
        {
            m_Options = options;
            CreateScope();
        }

        /// <summary>
        /// Default ctor.
        /// </summary>
        public DataContextScope()
        {
            CreateScope();
        }

        /// <summary>
        /// Creates a new DataContext within the scope of the current thread.
        /// </summary>
        private void CreateScope()
        {
            // create a unique key for this DataContext
            m_ContextKey = String.Format("__{0}_{1}", DateTime.UtcNow.Ticks, m_Random.Next(1000));

            // create a new DataContext for the current scope
            DataContext context = DataContextProvider.CreateDataContext(m_ContextKey, true);

            // set the options for the current DataContext before any connections
            // can be opened on the DataContext
            if (m_Options != null)
                context.LoadOptions = m_Options;
        }

        /// <summary>
        /// Gets the current DataLoadOptions
        /// </summary>
        /// <remarks>Any attempts to modify the DataLoadOptions will
        /// result in an exception being thrown by the .Net Framework</remarks>
        public DataLoadOptions LoadOptions
        {
            get
            {
                return m_Options;
            }
        }

        #region IDisposable Members

        protected bool IsDisposed { get; private set; }

        /// <summary>
        /// Verify the object has been disposed
        /// </summary>
        protected void CheckDisposed()
        {
            if (IsDisposed)
            {
                throw new ObjectDisposedException("DataContextScope");
            }
        }

        /// <summary>
        /// Dispose
        /// </summary>
        /// <param name="disposing"></param>
        public void Dispose(bool disposing)
        {
            if (!IsDisposed && disposing)
            {
                //clean up local resources
                DataContextProvider.RemoveDataContext(m_ContextKey, true);

                IsDisposed = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);

            // Suppress finalization of this disposed instance.
            GC.SuppressFinalize(this);
        }

        ~DataContextScope()
        {
            Dispose(false);
        }

        #endregion
    }
}
